package com.crcode.crm.service.accessory.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.crcode.crm.bean.accessory.AccessoryBean;
import com.crcode.crm.dao.accessory.AccessoryDao;
import com.crcode.crm.service.accessory.AccessoryService;
import com.crcode.crm.utils.PageVo;
import com.crcode.crm.utils.ResultUtil;
/**
 * 附件业务逻辑实现层
 * @author cl
 * @date 2019年3月26日
 */
@Service(value="accessoryService")
@Transactional
public class AccessoryServiceImpl implements AccessoryService {

	@Autowired
	private AccessoryDao accessoryDao;

	/**
	 * 根据序列化id查询
	 * @param serializable
	 * @return
	 */
	@Override
	public AccessoryBean getById(Integer serializable) {
		return accessoryDao.findById(serializable).get();
	}

	/**
	 * 保存返回实体
	 * @param t
	 * @return
	 */
	@Override
	public AccessoryBean saveResultBean(AccessoryBean t) {
		return accessoryDao.save(t);
	}

	/**
	 * 保存返回true或false
	 * @param t
	 * @return
	 */
	@Override
	public boolean saveResultBoolean(AccessoryBean t) {
		try {
			accessoryDao.save(t);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public AccessoryBean updateResultBean(AccessoryBean t) {
		return null;
	}

	/**
	 * 查询所有
	 * @return
	 */
	@Override
	public boolean updateResultBoolean(AccessoryBean t) {
		return false;
	}

	/**
	 * 根据序号删除
	 * @param serializable
	 * @return
	 */
	@Override
	public boolean delete(Integer serializable) {
		try {
			accessoryDao.deleteById(serializable);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public List<AccessoryBean> getAll() {
		return accessoryDao.findAll();
	}

	/**
	 * 分页条件查询
	 * @param params
	 * @param vo
	 * @return
	 */
	@Override
	public Map<String, Object> findAll(Map<String, Object> params, PageVo vo) {
		Integer pageIndex = vo.getPageIndex() - 1;
		Pageable pageable =null;
		if(StringUtils.isNotEmpty(vo.getOrderBy())){
			if(vo.getOrderDesc()==1){
				pageable =PageRequest.of(pageIndex, vo.getPageSize(),Direction.DESC, vo.getOrderBy());
			}else if(vo.getOrderDesc()==0){
				pageable =PageRequest.of(pageIndex, vo.getPageSize(),Direction.ASC, vo.getOrderBy());
			}	
		}else{
			pageable =PageRequest.of(pageIndex, vo.getPageSize());
		}
		Page<AccessoryBean> page = accessoryDao.findAll(spec(params), pageable);
		Map<String, Object> rm = new HashMap<String, Object>();
		rm.put("total", page.getTotalElements());
		rm.put("tatalPages", page.getTotalPages());
		rm.put("rows", page.getContent());
		return rm;
	}
	
	/**
	 * 创建动态查询条件组合
	 * @param params
	 * @return
	 */
    private Specification<AccessoryBean> spec(final Map<String,Object> params) {
    	Specification<AccessoryBean> spec = new Specification<AccessoryBean>() {
    		private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<AccessoryBean> root, CriteriaQuery<?> criteriaQuery,
					CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				//根据dataUUID查询
				if (params.get("dataUuid")!=null && params.get("dataUuid")!="") {
					predicates.add(cb.equal(root.get("dataUuid"), params.get("dataUuid")));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		};
        return spec;
    }

    /**
     * 根据主键批量物理删除
     * @param ids
     * @return
     */
	@Override
	public ResultUtil physicalDeleteByIds(String ids) {
		ResultUtil r = new ResultUtil();
		String [] arr = ids.split(",");
		List<Integer> list=new ArrayList<>();
		for (String str : arr) {
			list.add(Integer.parseInt(str));
		}
		long count=accessoryDao.deleteByIdIn(list);
		Boolean flag=true;
		if(count==0){
			flag=false;
		}
		r.setObj(null);
		r.setInfo(flag?"删除成功！":"删除失败！");
		r.setStatus(flag);
		return r;
	}
	
	/**
	 * 根据附件标题和关联档案UUID查询
	 * @param accTitle
	 * @param dataUuid
	 * @return
	 */
	public AccessoryBean findByAccTitleAndDataUuid(String accTitle,String dataUuid){
		return accessoryDao.findByAccTitleAndDataUuid(accTitle,dataUuid);
	}
}
